import axios from "axios"
import { ElMessage } from "element-plus"



let request = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 5000
})

request.interceptors.request.use(config => {
    //config配置对象，可以配置请求头，经常给服务器端携带公共参数
    //返回配置对象
    let token = localStorage.getItem("token")
    if(token){
        config.headers["token"] = token
    }

    return config
})
request.interceptors.response.use(response => {
    //成功的回调
    //简化数据
    return response.data
}, error => {
    //失败的回调
    let errorMsg = ""
    console.log(error);

    //根据不同的状态码，返回不同的错误信息，使用elementui的message组件
    let status = error.status;
    if (!status) {
        ElMessage({
            message: error.message,
            type: "error"
        })
        return Promise.reject(error)
    }
    switch (status) {
        case 401:
            errorMsg = "TOKEN失效，请重新登录"
            break;
        case 403:
            errorMsg = "没有权限"
            break;
        case 404:
            errorMsg = "请求地址不存在"
            break;
        case 500:
            errorMsg = "服务器内部错误"
            break;
        default:
            errorMsg = "未知错误"
    }
    ElMessage({
        message: errorMsg,
        type: "error"
    })
    return Promise.reject(error)
})


export default request